<template>
  <div class="fail">
    <input
      ref="failDrop"
      id="failDrop"
      type="file"
      @change="fileChange"
      style="opacity: 0; width: 100%; height: 100%; position: absolute; top: 0%; left: 0%; z-index: 999"
    />
    <div class="tishi">点击或者拖动上传</div>
  </div>
  <div class="imgList_" v-if="imageList.length != 0">
    <div class="image_father" v-for="(item, index) in imageList" :key="index">
      <template v-if="props.fileType == 'img'">
        <el-image
          style="width: 80px; height: 80px; z-index: 9999; border: 1px solid #dcdfe6; border-radius: 10px"
          :src="item"
          hide-on-click-modal
          fit="cover"
        />
        <el-icon :size="16" class="image_father_close" @click="deleteimg(index)">
          <CloseBold />
        </el-icon>
      </template>
      <template v-else-if="props.fileType == 'file'">
        <!-- @click.native="showFileFn(index)" -->
        <div>
          <el-tooltip class="box-item" effect="dark" :content="imageList[index]" placement="top-start">
            <el-input v-model="imageList[index]" disabled placeholder="Please input" />
          </el-tooltip>

          <el-icon :size="16" class="image_father_close" @click="deleteimg(index)">
            <CloseBold />
          </el-icon>
        </div>
        <div style="margin-top: 4px">
          <el-input v-model="filenameList[index]" placeholder="Please input" />
        </div>
      </template>
    </div>
    <el-dialog v-model="dialogTableVisible" title="Shipping address">
      <div id="yulan"></div>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { upLoadFile } from "@/api/file"
import { ref, reactive, onMounted, watch } from "vue"
import { ElMessage } from "element-plus"
import { img_type } from "@/hooks/common"

// import { defaultOptions, renderAsync } from "docx-preview";
// const { proxy } = getCurrentInstance() as ComponentInternalInstance

//#region 查看预览

let dialogTableVisible = ref<boolean>(false) // 弹框
// 文件缓存列表
const FileCatch = ref<any>([])
// 预览
const showFileFn = (i: number) => {
  dialogTableVisible.value = true
  //   setTimeout(()=>{
  //     console.log(document.getElementById("yulan"),'--showFileFn-');
  //     renderAsync(FileCatch.value[i],document.getElementById("yulan"), null,
  // {
  //        className:"docx", // 默认和文档样式类的类名/前缀
  //        inWrapper:  true, // 启用围绕文档内容渲染包装器
  //        ignoreWidth:  false, // 禁止页面渲染宽度
  //        ignoreHeight:   false, // 禁止页面渲染高度
  //        ignoreFonts:  false, // 禁止字体渲染
  //        breakPages:   true, // 在分页符上启用分页
  //        ignoreLastRenderedPageBreak:   true,//禁用lastRenderedPageBreak元素的分页
  //        experimental:   false, //启用实验性功能（制表符停止计算）
  //        trimXmlDeclaration:   true, //如果为真，xml声明将在解析之前从xml文档中删除
  //        debug:   false, // 启用额外的日志记录
  //    }
  // );
  //   },500)
}

//#endregion

const failDrop = ref<HTMLElement>()
const props = withDefaults(
  defineProps<{
    modelValue?: any //绑定数据
    maxNum?: number //上传最大类型限制
    url?: string //文件上传url地址
    failename?: string //文件名称
    needString?: boolean //是否返回string类型格式
    fileType?: string // 文件类型
    name?: string // 文件名字
    filecatch?: any // 文件类型
  }>(),
  {
    maxNum: 9,
    //默认图片上传
    url: "/file/upLoadFile",
    failename: "file",
    needString: true,
    fileType: "img",
    name: "",
    filecatch: ""
  }
)
const imageList = reactive<any>([])
const filenameList = reactive<string[]>([])
const emit = defineEmits<{
  (e: "update:modelValue", value: any): void
  (e: "update:name", value: any): void
  (e: "update:filecatch", value: any): void
  (e: "csvSuccess"): void
}>()

onMounted(() => {
  try {
    if (props.modelValue) {
      let arrurl = props.modelValue?.split(",") || []
      let arrurlName = props.name?.split(",") || []
      for (let i = 0; i < arrurl.length; i++) {
        imageList.push(arrurl[i])
        filenameList.push(arrurlName[i] || "")
      }
    }
  } catch (error) {
    imageList.push(props.modelValue)
    filenameList.push(props.name)
  }
  watch(
    [imageList, filenameList],
    (newValue) => {
      console.log("--watch-")

      if (props.needString) {
        emit("update:modelValue", newValue[0].join(","))
        emit("update:name", filenameList.join(","))
        console.log("FileCatch-2-", FileCatch.value[0])
        emit("update:filecatch", FileCatch.value[0])
        return
      }
      let value = ""
      let nameval = ""
      if (JSON.stringify(newValue[0]) !== "[]") {
        value = JSON.stringify(newValue[0])
        nameval = JSON.stringify(filenameList)
      }
      emit("update:modelValue", value)
      emit("update:name", nameval)
      console.log("FileCatch--", FileCatch.value)

      emit("update:filecatch", FileCatch.value[0])
    },
    {
      deep: true
    }
  )
  failDrop.value?.addEventListener(
    "drop",
    (ev) => {
      ev.preventDefault()
      const file = ev?.dataTransfer?.files[0]
      console.log(file, "文件")
      fileUpdate(file)
    },
    false
  )
})
const deleteimg = (index: number) => {
  //删除对应数据
  imageList.splice(index, 1)
  filenameList.splice(index, 1)
  FileCatch.value.splice(index, 1)
}
const fileChange = (e: any) => {
  const file = e.target.files[0]
  fileUpdate(file)
}
const fileUpdate = (file: any) => {
  if (imageList.length >= props.maxNum) {
    ElMessage({
      message: "图片数量超出,请删除已有数据！",
      type: "warning"
    })
    return
  }
  console.log(file, "--upLoadFile-")
  let filenamehz = file.name.substring(file.name.lastIndexOf("."))
  let filename = file.name.replace(filenamehz, "")
  //文件上传
  upLoadFile({ file }).then((res: any) => {
    console.log("---", res)

    if (props.failename == "send") {
      ElMessage.success("导入成功!")
      emit("csvSuccess")
      return
    }
    //上传限制约束
    const fileValue = res.data.nginxUrl // minIoUrl
    imageList.push(fileValue)
    filenameList.push(filename)
    FileCatch.value.push(file)
  })
}
</script>
<style scoped lang="scss">
#yulan {
  width: 90vw;
  height: 90vh;
}
.image_father {
  position: relative;
  width: 100%;
  margin-top: 10px;
  .image_father_close {
    position: absolute;
    top: 1%;
    right: 1%;
    z-index: 999999;
  }
}
.imgList_ {
  width: 100%;
  display: flex;
  margin-top: 20px;
  flex-wrap: wrap;

  .el-image {
    margin-left: 20px;
  }
}
.fail {
  width: 100%;
  height: 8vw;
  border: 1px solid #dcdfe6;
  position: relative;
  input {
    width: 100%;
    height: 100%;
  }
  .tishi {
    position: absolute;
    color: gray;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(50%);
    width: 100%;
    text-align: center;
    &::after {
      content: "";
      position: absolute;
      display: block;
      background: url("../../assets/power/yun.png") no-repeat;
      background-size: 100% 100%;
      // width: 100px;
      // height: 100px;

      // top: -265%;
      bottom: 19px;
      left: 50%;
      // margin-left: -50px;
      max-width: 100px;
      max-height: 100px;
      min-width: 50px;
      min-height: 50px;
      transform: translateX(-50%);
    }
  }
}
</style>
